import { useTaskStore } from '@/stores/taskStore';

const WS_BASE_URL = window.__env__.VITE_WS_BASE_URL || 'ws://127.0.0.1:8000/api/v1/ws';
const RETRY_DELAY = 3000;

let clientWebSocket: WebSocket | null = null;

// 建立客户端WebSocket连接
export function connectClientWebSocket() {
  const taskStore = useTaskStore();

  // 如果已经有连接，先关闭
  if (clientWebSocket) {
    clientWebSocket.close();
  }

  // 确保URL格式正确
  const wsUrl = `${WS_BASE_URL}/client/${taskStore.clientId}`;

  console.log(`建立客户端WebSocket连接: ${wsUrl}`);
  const ws = new WebSocket(wsUrl);

  ws.onopen = () => {
    console.log('客户端WebSocket连接已建立');
    taskStore.addNotification('info', '连接已建立', '已成功连接到服务器');
  };

  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);

      // 移除重复的处理逻辑，只保留switch语句
      switch (data.type) {
        case 'connection_id':
          taskStore.setConnectionId(data.connection_id);
          break;
        case 'task_status_update':
          console.log("task_status_update", data.data)
          taskStore.updateTaskStatus(data.task_id, data.data);
          break;
        case 'metadata_status_update':
          console.log("metadata_status_update", data.data)
          taskStore.updateMetadataStatus(data.task_id, data.data);
          break;
        case 'JiangSu_task_status_update':
          console.log("JiangSu_task_status_update", data.data) 
          taskStore.updateTaskStatus(data.task_id, data.data);
          break;
        case 'JiangSu_metadata_status_update':
          console.log("JiangSu_metadata_status_update", data.data) 
          taskStore.updateMetadataStatus(data.task_id, data.data);
          break;
        default:
          console.log('收到未知类型消息:', data);
      }

    } catch (error) {
      console.error('WebSocket消息处理错误:', error);
    }
  };

  ws.onerror = (error) => {
    console.error(`客户端WebSocket错误:`, error);
    taskStore.addNotification('error', '连接错误', '与服务器的连接发生错误');
  };

  ws.onclose = () => {
    console.log(`客户端WebSocket连接已关闭`);
    // 尝试重新连接
    setTimeout(() => connectClientWebSocket(), RETRY_DELAY);
  };

  // 保存WebSocket连接
  clientWebSocket = ws;

  return ws;
}

// 关闭WebSocket连接
export function closeWebSocket() {
  if (clientWebSocket) {
    clientWebSocket.close();
    clientWebSocket = null;
  }
}